import React, { useState } from "react";
import {
  Form,
  Input,
  Button,
  Select,
  Card,
  message,
  Modal,
  Alert,
  Checkbox,
  Typography,
} from "antd";
import {
  UserOutlined,
  LockOutlined,
  WifiOutlined,
  BookOutlined,
  TeamOutlined,
  SafetyOutlined,
} from "@ant-design/icons";
import { useNavigate, Link } from "react-router-dom";
import { useUser } from "../../contexts/UserContext";
import NetworkTest from "../../components/NetworkTest";

const { Title, Text } = Typography;

interface LoginForm {
  phone: string;
  password: string;
  type: "admin" | "teacher" | "student";
  rememberMe: boolean;
}

const Login: React.FC = () => {
  const navigate = useNavigate();
  const { login, loading, error } = useUser();
  const [showNetworkTest, setShowNetworkTest] = useState(false);
  const [networkError, setNetworkError] = useState(false);

  const onFinish = async (values: LoginForm) => {
    try {
      setNetworkError(false);
      console.log("🔐 登录请求参数:", {
        phone: values.phone,
        type: values.type,
        rememberMe: values.rememberMe,
        isPhone: /^1[3-9]\d{9}$/.test(values.phone),
        isEmail: /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.phone),
      });

      await login(
        values.phone,
        values.password,
        values.type,
        values.rememberMe
      );

      // 登录成功后根据角色跳转
      switch (values.type) {
        case "admin":
          navigate("/admin");
          break;
        case "teacher":
          navigate("/teacher");
          break;
        case "student":
          navigate("/student");
          break;
        default:
          navigate("/");
      }
    } catch (error: any) {
      console.error("❌ 登录错误:", error);

      // 检查是否是网络连接问题
      const isNetworkError =
        error?.code === "ECONNREFUSED" ||
        error?.code === "NETWORK_ERROR" ||
        error?.message?.includes("Network Error") ||
        error?.message?.includes("网络连接失败") ||
        error?.message?.includes("网络连接失败") ||
        !error?.response; // 没有响应通常表示网络问题

      if (isNetworkError) {
        setNetworkError(true);
        message.error({
          content: (
            <div>
              网络连接失败，请检查后端服务是否启动
              <br />
              <Button
                type="link"
                size="small"
                onClick={() => setShowNetworkTest(true)}
                icon={<WifiOutlined />}
              >
                点击诊断网络问题
              </Button>
            </div>
          ),
          duration: 6,
        });
      }
      // 错误消息已在useAuth中自动显示，无需重复显示
    }
  };

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        minHeight: "100vh",
        background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
        position: "relative",
        overflow: "hidden",
      }}
    >
      {/* 背景装饰 */}
      <div
        style={{
          position: "absolute",
          top: "-50%",
          left: "-50%",
          width: "200%",
          height: "200%",
          background: `
            radial-gradient(circle at 20% 80%, rgba(120, 119, 198, 0.3) 0%, transparent 50%),
            radial-gradient(circle at 80% 20%, rgba(255, 119, 198, 0.3) 0%, transparent 50%),
            radial-gradient(circle at 40% 40%, rgba(120, 219, 255, 0.2) 0%, transparent 50%)
          `,
          animation: "float 6s ease-in-out infinite",
        }}
      />

      <Card
        style={{
          width: 420,
          maxWidth: "90vw",
          boxShadow: "0 20px 60px rgba(0, 0, 0, 0.2)",
          borderRadius: "20px",
          border: "none",
          backdropFilter: "blur(10px)",
          background: "rgba(255, 255, 255, 0.95)",
          position: "relative",
          zIndex: 1,
        }}
        styles={{
          body: {
            padding: "40px 32px",
          }
        }}
      >
        {/* 系统标题区域 */}
        <div style={{ textAlign: "center", marginBottom: 32 }}>
          <div
            style={{
              display: "inline-flex",
              alignItems: "center",
              justifyContent: "center",
              width: "64px",
              height: "64px",
              background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
              borderRadius: "50%",
              marginBottom: "16px",
              boxShadow: "0 8px 24px rgba(102, 126, 234, 0.3)",
            }}
          >
            <BookOutlined style={{ fontSize: "28px", color: "white" }} />
          </div>

          <Title
            level={2}
            style={{
              margin: 0,
              background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
              WebkitBackgroundClip: "text",
              WebkitTextFillColor: "transparent",
              fontSize: "28px",
              fontWeight: "700",
              letterSpacing: "1px",
            }}
          >
            智教质学平台
          </Title>

          <Text
            style={{
              color: "#8c8c8c",
              fontSize: "14px",
              display: "block",
              marginTop: "8px",
            }}
          >
            智慧教学，质量为先
          </Text>
        </div>

        {networkError && (
          <Alert
            message="网络连接问题"
            description={
              <div>
                无法连接到后端服务，请确认：
                <br />• 后端服务已启动 (端口8080)
                <br />• 网络连接正常
                <br />
                <Button
                  type="link"
                  size="small"
                  icon={<WifiOutlined />}
                  onClick={() => setShowNetworkTest(true)}
                  style={{ padding: 0, height: "auto" }}
                >
                  运行网络诊断
                </Button>
              </div>
            }
            type="warning"
            showIcon
            style={{ marginBottom: 16 }}
            closable
            onClose={() => setNetworkError(false)}
          />
        )}

        <Form<LoginForm>
          name="login"
          initialValues={{
            type: "teacher",
            rememberMe: true,
          }}
          onFinish={onFinish}
          size="large"
        >
          <Form.Item
            name="phone"
            rules={[
              { required: true, message: "请输入手机号或邮箱" },
              {
                validator: (_, value) => {
                  if (!value) return Promise.resolve();

                  const isPhone = /^1[3-9]\d{9}$/.test(value);
                  const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value);

                  if (isPhone || isEmail) {
                    return Promise.resolve();
                  }

                  return Promise.reject(new Error("请输入正确的手机号或邮箱"));
                },
              },
            ]}
          >
            <Input
              prefix={<UserOutlined style={{ color: "#8c8c8c" }} />}
              placeholder="手机号或邮箱"
              style={{
                height: "48px",
                borderRadius: "12px",
                fontSize: "16px",
                border: "2px solid #f0f0f0",
                transition: "all 0.3s ease",
              }}
              onFocus={(e) => {
                e.target.style.borderColor = "#667eea";
                e.target.style.boxShadow = "0 0 0 2px rgba(102, 126, 234, 0.1)";
              }}
              onBlur={(e) => {
                e.target.style.borderColor = "#f0f0f0";
                e.target.style.boxShadow = "none";
              }}
            />
          </Form.Item>

          <Form.Item
            name="password"
            rules={[
              { required: true, message: "请输入密码" },
              { min: 6, message: "密码至少6位" },
            ]}
          >
            <Input.Password
              prefix={<LockOutlined style={{ color: "#8c8c8c" }} />}
              placeholder="密码"
              style={{
                height: "48px",
                borderRadius: "12px",
                fontSize: "16px",
                border: "2px solid #f0f0f0",
                transition: "all 0.3s ease",
              }}
              onFocus={(e) => {
                e.target.style.borderColor = "#667eea";
                e.target.style.boxShadow = "0 0 0 2px rgba(102, 126, 234, 0.1)";
              }}
              onBlur={(e) => {
                e.target.style.borderColor = "#f0f0f0";
                e.target.style.boxShadow = "none";
              }}
            />
          </Form.Item>

          <Form.Item
            name="type"
            rules={[{ required: true, message: "请选择角色" }]}
          >
            <Select
              placeholder="选择您的身份"
              style={{
                height: "48px",
                borderRadius: "12px",
              }}
              styles={{
                popup: {
                  root: {
                    borderRadius: "12px",
                    boxShadow: "0 8px 24px rgba(0, 0, 0, 0.15)",
                  }
                }
              }}
            >
              <Select.Option value="admin">
                <div
                  style={{ display: "flex", alignItems: "center", gap: "8px" }}
                >
                  <SafetyOutlined style={{ color: "#f5222d" }} />
                  <span>管理员</span>
                </div>
              </Select.Option>
              <Select.Option value="teacher">
                <div
                  style={{ display: "flex", alignItems: "center", gap: "8px" }}
                >
                  <TeamOutlined style={{ color: "#1890ff" }} />
                  <span>教师</span>
                </div>
              </Select.Option>
              <Select.Option value="student">
                <div
                  style={{ display: "flex", alignItems: "center", gap: "8px" }}
                >
                  <BookOutlined style={{ color: "#52c41a" }} />
                  <span>学生</span>
                </div>
              </Select.Option>
            </Select>
          </Form.Item>

          <Form.Item name="rememberMe" valuePropName="checked">
            <Checkbox
              style={{
                color: "#8c8c8c",
                fontSize: "14px",
              }}
            >
              记住我 (7天内自动登录)
            </Checkbox>
          </Form.Item>

          <Form.Item style={{ marginBottom: "16px" }}>
            <Button
              type="primary"
              htmlType="submit"
              loading={loading}
              style={{
                width: "100%",
                height: "48px",
                fontSize: "16px",
                fontWeight: "600",
                borderRadius: "12px",
                background: "linear-gradient(135deg, #667eea 0%, #764ba2 100%)",
                border: "none",
                boxShadow: "0 4px 12px rgba(102, 126, 234, 0.3)",
                transition: "all 0.3s ease",
              }}
              onMouseEnter={(e) => {
                e.currentTarget.style.transform = "translateY(-2px)";
                e.currentTarget.style.boxShadow =
                  "0 6px 20px rgba(102, 126, 234, 0.4)";
              }}
              onMouseLeave={(e) => {
                e.currentTarget.style.transform = "translateY(0)";
                e.currentTarget.style.boxShadow =
                  "0 4px 12px rgba(102, 126, 234, 0.3)";
              }}
            >
              登录
            </Button>
          </Form.Item>
        </Form>

        <div style={{ textAlign: "center", marginTop: 16 }}>
          <Link
            to="/register"
            style={{
              color: "#667eea",
              textDecoration: "none",
              fontSize: "14px",
              transition: "all 0.3s ease",
            }}
            onMouseEnter={(e) => {
              e.currentTarget.style.color = "#764ba2";
            }}
            onMouseLeave={(e) => {
              e.currentTarget.style.color = "#667eea";
            }}
          >
            没有账号？立即注册
          </Link>
        </div>
      </Card>

      {/* 网络测试弹窗 */}
      <Modal
        title="网络连接诊断"
        open={showNetworkTest}
        onCancel={() => setShowNetworkTest(false)}
        footer={null}
        width={600}
        style={{
          borderRadius: "12px",
        }}
      >
        <NetworkTest />
      </Modal>

      {/* 添加CSS动画 */}
      <style>{`
        @keyframes float {
          0%, 100% { transform: translateY(0px) rotate(0deg); }
          33% { transform: translateY(-30px) rotate(1deg); }
          66% { transform: translateY(-20px) rotate(-1deg); }
        }
        
        .ant-select-dropdown .ant-select-item:hover {
          background-color: rgba(102, 126, 234, 0.05) !important;
        }
        
        .ant-input:focus, .ant-input-password:focus {
          border-color: #667eea !important;
          box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1) !important;
        }
        
        .ant-select-focused .ant-select-selector {
          border-color: #667eea !important;
          box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.1) !important;
        }
      `}</style>
    </div>
  );
};

export default Login;
